package com.anywhere.freightman.order.controller;

import com.anywhere.freightman.common.ContextKeys;
import com.anywhere.freightman.common.annotation.Permission;
import com.anywhere.freightman.common.entity.ReturnResp;
import com.anywhere.freightman.common.entity.order.WaybillQueryEntity;
import com.anywhere.freightman.common.entity.user.Account;
import com.anywhere.freightman.common.enumeration.RoleType;
import com.anywhere.freightman.common.enumeration.WaybillStatus;
import com.anywhere.freightman.common.ex.CustomException;
import com.anywhere.freightman.common.request.PageRequest;
import com.anywhere.freightman.order.controller.request.BindCarAndDriverRequest;
import com.anywhere.freightman.order.controller.request.WaybillOneRequest;
import com.anywhere.freightman.order.controller.request.WaybillRequest;
import com.anywhere.freightman.order.controller.resp.WaybillDetailsResp;
import com.anywhere.freightman.order.controller.resp.WaybillResp;
import com.anywhere.freightman.order.model.AddressBookModel;
import com.anywhere.freightman.order.model.WaybillModel;
import com.anywhere.freightman.order.service.IAddressBookService;
import com.anywhere.freightman.order.service.IGoodsService;
import com.anywhere.freightman.order.service.IWaybillLogService;
import com.anywhere.freightman.order.service.IWaybillService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("waybill")
public class WaybillController {

    @Autowired
    private IWaybillService waybillService;
    @Autowired
    private IAddressBookService addressBookService;
    @Autowired
    private IWaybillLogService waybillLogService;
    @Autowired
    private IGoodsService goodsService;

    @Permission(code = "PROJECT")
    @GetMapping("page")
    @ApiOperation("分页")
    public PageInfo<WaybillResp> getPageList(HttpServletRequest httpRequest,
                                             WaybillQueryEntity qm) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        PageRequest<WaybillQueryEntity> pageRequest = new PageRequest<>();
        if (!account.getType().equals(RoleType.ADMIN)) {
            qm.setCompanyId(account.getCompanyId());
        }
        BeanUtils.copyProperties(qm, pageRequest);
        pageRequest.setEntity(qm);

        PageInfo<WaybillModel> pageList = waybillService.getPageList(pageRequest);

        PageInfo<WaybillResp> resp = new PageInfo<>();
        BeanUtils.copyProperties(pageList, resp);
        List<WaybillResp> list = new ArrayList<>();
        pageList.getList().forEach(item -> {
            WaybillResp response = new WaybillResp();
            BeanUtils.copyProperties(item, response);
            AddressBookModel receiver = addressBookService.getById(item.getReceiverId());
            response.setReceiver(receiver);
            AddressBookModel shipper = addressBookService.getById(item.getShipperId());
            response.setShipper(shipper);

            list.add(response);
        });
        /*for (int i = 0; i < pageList.getList().size(); i++) {
            WaybillModel item = pageList.getList().get(i);

        }*/
        resp.setList(list);

        return resp;
    }

    @Permission(code = "PROJECT")
    @GetMapping("details/{orderNo}")
    @ApiOperation("详情")
    public ReturnResp getDetails(HttpServletRequest httpRequest,
                                 @PathVariable("orderNo") String orderNo) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || (!account.getType().equals(RoleType.ADMIN)
                && !account.getCompanyId().equals(waybill.getCompanyId()))) {
            throw new CustomException("运单信息不存在");
        }
        WaybillDetailsResp resp = new WaybillDetailsResp();
        BeanUtils.copyProperties(waybill, resp);

        resp.setReceiver(addressBookService.getById(resp.getReceiverId()));
        resp.setShipper(addressBookService.getById(resp.getShipperId()));

        resp.setGoodsList(goodsService.getListByOrderNo(orderNo));
        resp.setCarAndDriverList(waybillService.getListCarAndDriver(orderNo));
        resp.setLogs(waybillLogService.getListByOrderNo(orderNo));

        resp.setFileList(waybillService.getFileList(orderNo));

        return ReturnResp.buildOk(resp);
    }

    @Permission(code = "PROJECT")
    @PostMapping
    @ApiOperation("创建订单")
    public ReturnResp save(HttpServletRequest httpRequest,
                           @RequestBody WaybillRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        waybillService.insert(request, account.getCompanyId());
        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @PostMapping("one")
    @ApiOperation("创建订单")
    public ReturnResp saveOne(HttpServletRequest httpRequest,
                              @RequestBody WaybillOneRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        waybillService.insertOne(request, account.getCompanyId());
        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @PostMapping("/bind/car")
    @ApiOperation("绑定车辆和司机")
    public ReturnResp bindCarAndDriver(HttpServletRequest httpRequest,
                                       @RequestBody BindCarAndDriverRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        WaybillModel waybill = waybillService.getByNo(request.getOrderNo());
        if (waybill == null || (!account.getType().equals(RoleType.ADMIN)
                && !account.getCompanyId().equals(waybill.getCompanyId()))) {
            throw new CustomException("运单信息不存在");
        }
        waybillService.bindCarAndDriver(request.getOrderNo(), request.getCarId(), request.getDriverId());
        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @PostMapping("/access/car/driver/{id}")
    @ApiOperation("绑定车辆和司机")
    public ReturnResp bindCarAndDriver(HttpServletRequest httpRequest,
                                       @PathVariable("id") Long id) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        waybillService.accessCarDriver(id, account);
        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @DeleteMapping("/bind/car")
    @ApiOperation("解绑车辆和司机")
    public ReturnResp bindCarAndDriver(HttpServletRequest httpRequest,
                                       @RequestParam("orderNo") String orderNo,
                                       @RequestParam("id") Long id) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || !waybill.getCompanyId().equals(account.getCompanyId())) {
            throw new CustomException("没有找到该订单号");
        }
        if (!waybill.getStatus().equals(WaybillStatus.CREATED) && !waybill.getStatus().equals(WaybillStatus.WAIT_PICK)) {
            throw new CustomException("订单状态错误");
        }
        waybillLogService.insert(orderNo, "移除车辆和司机");
        waybillService.removeCarAndDriver(id);
        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @PutMapping("{orderNo}/send/river")
    @ApiOperation("下发至司机")
    public ReturnResp sendToDriver(HttpServletRequest httpRequest,
                                   @PathVariable("orderNo") String orderNo) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || !waybill.getCompanyId().equals(account.getCompanyId())) {
            throw new CustomException("没有找到该订单号!");
        }

        if (!waybill.getStatus().equals(WaybillStatus.CREATED)) {
            throw new CustomException("订单状态错误");
        }

        waybillService.sentToDriver(orderNo);

        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @PutMapping("{orderNo}/pay")
    @ApiOperation("支付确认")
    public ReturnResp payMark(HttpServletRequest httpRequest,
                              @PathVariable("orderNo") String orderNo) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || !waybill.getCompanyId().equals(account.getCompanyId())) {
            throw new CustomException("没有找到该订单号!!");
        }

        if (!waybill.getStatus().equals(WaybillStatus.WAIT_PAY)) {
            throw new CustomException("订单状态错误");
        }

        waybillService.payMark(orderNo);

        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @PutMapping("{orderNo}/confirm")
    @ApiOperation("订单确认")
    public ReturnResp confirmOrder(HttpServletRequest httpRequest,
                                   @PathVariable("orderNo") String orderNo) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || !waybill.getCompanyId().equals(account.getCompanyId())) {
            throw new CustomException("订单号错误，没有找到订单信息");
        }

        if (!waybill.getStatus().equals(WaybillStatus.WAIT_PICK)) {
            throw new CustomException("订单状态错误");
        }

        waybillService.confirmOrder(orderNo);

        return ReturnResp.buildOk();
    }

    @Permission(code = "PROJECT")
    @PutMapping("{orderNo}/close")
    @ApiOperation("订单取消")
    public ReturnResp closeOrder(HttpServletRequest httpRequest,
                                 @PathVariable("orderNo") String orderNo) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        WaybillModel waybill = waybillService.getByNo(orderNo);
        if (waybill == null || !waybill.getCompanyId().equals(account.getCompanyId())) {
            throw new CustomException("订单号错误，没有找到订单信息!");
        }
        waybillService.close(orderNo);

        return ReturnResp.buildOk();
    }
}
